package com.yxr.controller;

import com.yxr.domain.ResponseResult;
import com.yxr.domain.entity.LoginUser;
import com.yxr.domain.entity.Menu;
import com.yxr.domain.entity.User;
import com.yxr.domain.exception.SystemException;
import com.yxr.domain.vo.AdminUserInfoVo;
import com.yxr.domain.vo.RouterVo;
import com.yxr.domain.vo.UserInfoVo;
import com.yxr.enums.AppHttpCodeEnum;
import com.yxr.service.LoginService;
import com.yxr.service.MenuService;
import com.yxr.service.RoleService;
import com.yxr.utils.BeanCopyUtils;
import com.yxr.utils.RedisCache;
import com.yxr.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController

public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RedisCache redisCache;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        if (!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        return loginService.login(user);
    }

    @GetMapping("/getInfo")
    public ResponseResult<AdminUserInfoVo> getInfo(){
        //获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        //根据用户id查询权限信息
        List<String> perms = menuService.selectPeremsByUserId(loginUser.getUser().getId());
        //角色信息
        List<String> roleKeyList = roleService.selectRoleKeyByUserId(loginUser.getUser().getId());
        //封装返回
        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(perms,roleKeyList,userInfoVo);

        return ResponseResult.okResult(adminUserInfoVo);
    }

    @GetMapping("/getRouters")
    public ResponseResult<RouterVo> getRouters(){
        Long userId = SecurityUtils.getUserId();
        //查询menu 结果是tree的形式
        List<Menu> menus = menuService.selectRouterMenuTreeByUserId(userId);
        //封装数据返回
        return ResponseResult.okResult(new RouterVo(menus));

    }

    @PostMapping("/user/logout")
    public ResponseResult logout(){
      return loginService.loginout();
    }


}
